package com.project.harmonyledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.harmonyledger.common.response.Result;
import com.project.harmonyledger.common.response.ResultCode;
import com.project.harmonyledger.mapper.AccountMapper;
import com.project.harmonyledger.pojo.Account;
import com.project.harmonyledger.pojo.User;
import com.project.harmonyledger.service.AccountService;
import com.project.harmonyledger.utils.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {
  @Autowired
  private AccountMapper accountMapper;

  // 获取当前登录用户
  private User getCurrentUser() {
    UserDetailsImpl loginUser = (UserDetailsImpl) SecurityContextHolder.getContext()
        .getAuthentication().getPrincipal();
    log.info("当前登录用户: {}", loginUser.toString());
    return loginUser.getUser();
  }

  // 验证账户所有权
  private boolean validateAccountOwnership(Account account) {
    return !account.getUserId().equals(getCurrentUser().getId().longValue());
  }

  @Override
  @Transactional
  public Result<Map<String, String>> createAccount(Account account) {
    Map<String, String> map = new HashMap<>();

    // 设置当前用户ID，防止伪造
    account.setUserId(getCurrentUser().getId().longValue());

    // 参数验证
    if (account.getName() == null || account.getName().trim().isEmpty()) {
      map.put("message", "账户名称不能为空");
      return Result.error(ResultCode.BAD_REQUEST, map);
    }
    if (account.getAccountTypeId() == null) {
      map.put("message", "账户类型不能为空");
      return Result.error(ResultCode.BAD_REQUEST, map);
    }

    QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
    accountQueryWrapper
        .eq("user_id", account.getUserId())
        .eq("account_type_id", account.getAccountTypeId());

    List<Account> existingAccounts = accountMapper.selectList(accountQueryWrapper);
    if (!existingAccounts.isEmpty()) {
      map.put("message", ResultCode.ACCOUNT_EXISTS.getMessage());
      return Result.error(ResultCode.ACCOUNT_EXISTS, map);
    }

    try {
      // 设置初始值
      account.setBalance(new BigDecimal("0.00")); // 初始余额设为0
      account.setCreatedAt(new Date());
      account.setUpdatedAt(new Date());

      // 保存账户到数据库
      accountMapper.insert(account);
      return Result.success(result(account));

    } catch (Exception e) {
      log.error("创建账户失败: {}", e.getMessage());
      map.put("message", "创建账户失败：" + e.getMessage());
      return Result.error(ResultCode.SYSTEM_ERROR, map);
    }
  }

  /**
   * 根据账户ID获取账户信息
   *
   * @param id
   * @return
   */
  @Override
  public Result<Map<String, String>> getAccountById(Long id) {
    Map<String, String> map = new HashMap<>();
    if (id == null) {
      map.put("message", "账户ID不能为空");
      return Result.error(ResultCode.BAD_REQUEST, map);
    }

    Account account = accountMapper.selectById(id);
    if (account == null) {
      map.put("message", "账户不存在");
      return Result.error(ResultCode.ACCOUNT_NOT_FOUND, map);
    }

    // 验证账户所有权
    if (validateAccountOwnership(account)) {
      map.put("message", "无权访问该账户");
      return Result.error(ResultCode.FORBIDDEN, map);
    }

    return Result.success(result(account));
  }

  /**
   * 获取当前用户的所有账户信息
   *
   * @return
   */
  @Override
  public Result<List<Account>> getUserAccounts(String userId) {
    // 验证用户权限
    if (!getCurrentUser().getId().toString().equals(userId)) {
      return Result.error(ResultCode.FORBIDDEN);
    }

    QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id", userId);
    return Result.success(accountMapper.selectList(queryWrapper));
  }

  @Override
  public Result<Map<String, String>> updateBalance(Long accountId, BigDecimal amount) {
    Map<String, String> map = new HashMap<>();
    if (accountId == null || amount == null) {
      map.put("message", "账户ID和金额不能为空");
      return Result.error(ResultCode.BAD_REQUEST, map);
    }

    Account account = accountMapper.selectById(accountId);
    if (account == null) return Result.error(ResultCode.ACCOUNT_NOT_FOUND);

    // 验证账户所有权
    if (validateAccountOwnership(account)) return Result.error(ResultCode.FORBIDDEN, map);

    account.setBalance(account.getBalance().add(amount));
    accountMapper.updateById(account);
    map.put("message", "余额更新成功");
    return Result.success(map);
  }

  @Override
  public Result<Map<String, String>> getAccountSummary(Long accountId) {
    Map<String, String> map = new HashMap<>();
    if (accountId == null) {
      map.put("message", "账户ID不能为空");
      return Result.error(ResultCode.BAD_REQUEST, map);
    }

    Account account = accountMapper.selectById(accountId);
    if (account == null) {
      map.put("message", "账户不存在");
      return Result.error(ResultCode.ACCOUNT_NOT_FOUND, map);
    }

    // 验证账户所有权
    if (validateAccountOwnership(account)) {
      map.put("message", "无权访问该账户");
      return Result.error(ResultCode.FORBIDDEN, map);
    }

    // TODO: 实现账户统计逻辑
    return Result.success(null);
  }

  public Map<String, String> result(Account account) {
    Map<String, String> map = new HashMap<>();
    map.put("userId", account.getUserId().toString());
    map.put("accountTypeId", account.getAccountTypeId().toString());
    map.put("name", account.getName());
    map.put("balance", account.getBalance().toString());
    map.put("createdAt", account.getCreatedAt().toString());
    map.put("updatedAt", account.getUpdatedAt().toString());
    return map;
  }
}

 
